import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import {
  List,
  Card,
  Tag,
  Button,
  Select,
  Typography,
  Modal,
  Form,
  Input,
  InputNumber,
  message,
  Spin,
  Popconfirm,
} from "antd";
import {
  PlusOutlined,
  GiftOutlined,
  FireOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import { BountyProvider, useBounty } from "./BountyContext";
import "./style.styl";

const { Title, Paragraph } = Typography;
const { TextArea } = Input;
const { Option } = Select;

// 悬赏列表内容组件
const BountyListContent = () => {
  // 所有悬赏任务
  const [bounties, setBounties] = useState([]);
  // 加载中遮罩
  const [loading, setLoading] = useState(false);
  // 创建悬赏任务弹窗
  const [modalVisible, setModalVisible] = useState(false);
  // 提交悬赏任务请求中，控制按钮禁止点击
  const [submitting, setSubmitting] = useState(false);
  // 分页信息
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [filters, setFilters] = useState({
    status: "all",
    sort: "newest",
  });
  const navigate = useNavigate();
  const [form] = Form.useForm();

  // 使用bounty上下文
  const { getBountyList, createBounty, deleteBounty, currentUser } =
    useBounty();

  const loadBounties = async (page = 1, filters = {}) => {
    setLoading(true);
    try {
      const res = await getBountyList({
        page,
        size: pagination.pageSize,
        ...filters,
      });
      setBounties(res.data.list || []);
      setPagination({
        ...pagination,
        current: page,
        total: res.data.total || 0,
      });
    } catch (error) {
      console.error("加载悬赏任务失败:", error);
      message.error("加载悬赏任务失败，请稍后重试");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadBounties(pagination.current, filters);
  }, [filters]);

  const handlePageChange = (page) => {
    loadBounties(page, filters);
  };

  const handleFilterChange = (name, value) => {
    setFilters({ ...filters, [name]: value });
  };

  const openCreateModal = () => {
    setModalVisible(true);
    form.resetFields();
  };

  const handleCreateBounty = async (values) => {
    setSubmitting(true);
    try {
      await createBounty(values);
      console.log("悬赏任务发布成功");
      message.success("悬赏任务发布成功");
      setModalVisible(false);
      loadBounties(1, filters);
    } catch (error) {
      console.error("发布悬赏任务失败:", error);
      message.error("发布失败，请稍后重试");
    } finally {
      setSubmitting(false);
    }
  };

  const handleDeleteBounty = async (id) => {
    try {
      await deleteBounty(id);
      message.success("悬赏任务已删除");
      loadBounties(pagination.current, filters);
    } catch (error) {
      console.error("删除悬赏任务失败:", error);
      message.error("删除失败，请稍后重试");
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case "active":
        return "green";
      case "completed":
        return "blue";
      case "expired":
        return "red";
      default:
        return "default";
    }
  };

  const getStatusText = (status) => {
    switch (status) {
      case "active":
        return "进行中";
      case "completed":
        return "已完成";
      case "expired":
        return "已过期";
      default:
        return "未知状态";
    }
  };

  // 判断用户是否是发布者
  const isPublisher = (publisher) => {
    return publisher && publisher.id === currentUser.id;
  };

  return (
    <div className="bounty-list-container">
      <div className="bounty-header">
        <Title level={2}>资源悬赏</Title>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={openCreateModal}
          className="publish-button"
        >
          发布资源悬赏
        </Button>
      </div>

      <div className="filter-bar">
        <span className="filter-label">状态：</span>
        <Select
          defaultValue="all"
          style={{ width: 120 }}
          onChange={(value) => handleFilterChange("status", value)}
        >
          <Option value="all">全部</Option>
          <Option value="active">进行中</Option>
          <Option value="completed">已完成</Option>
          <Option value="expired">已过期</Option>
        </Select>

        <span className="filter-label">排序：</span>
        <Select
          defaultValue="newest"
          style={{ width: 150 }}
          onChange={(value) => handleFilterChange("sort", value)}
        >
          <Option value="newest">最新发布</Option>
          <Option value="reward_desc">奖励从高到低</Option>
          <Option value="reward_asc">奖励从低到高</Option>
        </Select>
      </div>

      {loading ? (
        <div className="loading-container">
          <Spin size="large" tip="数据加载中..." />
        </div>
      ) : (
        <List
          className="bounty-list"
          grid={{ gutter: 16, xs: 1, sm: 2, md: 2, lg: 3, xl: 3, xxl: 4 }}
          dataSource={bounties}
          pagination={{
            onChange: handlePageChange,
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showTotal: (total) => `共 ${total} 个悬赏`,
            showSizeChanger: false,
          }}
          renderItem={(item) => (
            <List.Item>
              <Card
                hoverable
                className="bounty-card"
                onClick={() => navigate(`/community/bounty/${item.id}`)}
                actions={
                  isPublisher(item.publisher)
                    ? [
                        <Popconfirm
                          title="确定要删除此悬赏任务吗？"
                          onConfirm={(e) => {
                            e.stopPropagation();
                            handleDeleteBounty(item.id);
                          }}
                          onCancel={(e) => e.stopPropagation()}
                        >
                          <DeleteOutlined
                            onClick={(e) => e.stopPropagation()}
                            key="delete"
                          />
                        </Popconfirm>,
                      ]
                    : []
                }
              >
                <div className="bounty-card-header">
                  <Tag color={getStatusColor(item.status)}>
                    {getStatusText(item.status)}
                  </Tag>
                  <div className="bounty-reward">
                    <GiftOutlined /> {item.reward} 魔力值
                  </div>
                </div>
                <Title level={4} className="bounty-title">
                  {item.title}
                </Title>
                <div className="bounty-info">
                  <div className="bounty-publisher">
                    发布者: {item.publisher.username}
                  </div>
                  <div className="bounty-date">
                    {new Date(item.createdAt).toLocaleDateString()}
                  </div>
                </div>
              </Card>
            </List.Item>
          )}
        />
      )}

      {/* 创建悬赏任务弹窗 */}
      <Modal
        title="发布资源悬赏"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form form={form} layout="vertical" onFinish={handleCreateBounty}>
          <Form.Item
            name="title"
            label="悬赏标题"
            rules={[
              { required: true, message: "请输入悬赏标题" },
              { max: 50, message: "标题不能超过50个字符" },
            ]}
          >
            <Input placeholder="请输入悬赏标题" maxLength={50} showCount />
          </Form.Item>

          <Form.Item
            name="description"
            label="需求描述"
            rules={[
              { required: true, message: "请输入需求描述" },
              { max: 500, message: "描述不能超过500个字符" },
            ]}
          >
            <TextArea
              placeholder="请详细描述您的资源需求..."
              rows={6}
              maxLength={500}
              showCount
            />
          </Form.Item>

          <Form.Item
            name="reward"
            label="奖励魔力值"
            rules={[
              { required: true, message: "请输入奖励魔力值" },
              {
                type: "number",
                min: 0,
                max: 10000,
                message: "奖励范围为0-10000",
              },
            ]}
          >
            <InputNumber
              placeholder="请输入奖励魔力值"
              style={{ width: "100%" }}
              min={0}
              max={10000}
            />
          </Form.Item>

          <div className="form-actions">
            <Button onClick={() => setModalVisible(false)}>取消</Button>
            <Button type="primary" htmlType="submit" loading={submitting}>
              发布悬赏
            </Button>
          </div>
        </Form>
      </Modal>
    </div>
  );
};

// 主组件，包含Provider
// const BountyList = () => {
//   return (
//     <BountyProvider>
//       <BountyListContent />
//     </BountyProvider>
//   );
// };

export default BountyListContent;
